package com.emptyMe.product.service.imp;

import com.emptyMe.basic.utils.AjaxResult;
import com.emptyMe.product.domain.Product;
import com.emptyMe.product.mapper.ProductMapper;
import com.emptyMe.product.query.ProductQuery;
import com.emptyMe.product.service.IProductService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ProductServiceImpl implements IProductService {

    @Autowired
    private ProductMapper mapper;

    /**
     * 分页查询 + 模糊查询
     * @param query 查询依据 页数 页大小
     * @return
     */
    @Override
    public AjaxResult loadAll(ProductQuery query) {
        PageHelper.startPage(query.getCurrentPage(), query.getPageSize());
        Page<Product> page = (Page<Product>) mapper.getAll(query);
        PageInfo<Product> info = page.toPageInfo();
        return AjaxResult.me(info);
    }

    @Override
    public AjaxResult addOrUpdate(Product product) {
        if (product.getId()==null){
            try {
                mapper.save(product);
                return AjaxResult.me();
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.me(false,"添加失败-"+e.getCause());
            }
        }else {
            try {
                mapper.update(product);
                return AjaxResult.me();
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.me(false,"修改失败-"+e.getMessage());
            }
        }
    }

    @Override
    public AjaxResult remove(Long id) {
        try {
            mapper.remove(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me(false, "删除失败--" + e.getCause());
        }
    }

    @Override
    public AjaxResult removeMany(List<Product> products) {
        try {
            for (Product product : products) {
                mapper.remove(product.getId());
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me(false, "删除失败--" + e.getCause());
        }
    }
}
